const Class = require('../models/classmodel')
const User = require('../models/usermodel')
const SCLtest = require('../models/SCLtestmodel')

//查看班级
exports.class_view = async (req, res) => {
    try {
        var class_all = await Class.find({},{class_id: 1,class_name: 1,_id: 0},{sort: {_id: -1}});
        res.status(200).json({
            message: "success",
            class_all
        })
        // console.log(class_all)
    } catch (err) {
        // console.log(err)
        res.status(400).json({ message: err });
    }
}

//新建班级
exports.class_create = async (req, res) => {
    try{
        var class_id = req.body.class_id ;
        var class_name = req.body.class_name;
        var class_ = await Class.findOne({class_id: class_id})
        if(class_){
                res.status(402).json({
                message: "class number conflict"
            })
        }
        else{
            await Class.create({
                class_id: class_id,
                class_name: class_name
            })
            res.status(200).json({
            message: "success"
            })
        }    
    }
    catch(err){
        res.status(400).json({
            message: err
        })
    }
}

//删除班级,需要测试
exports.class_delete = async (req, res) => {
    try {
        var person = await User.find({$and: [{class_id: req.body.class_id},{identity: 0}]},
            {person_id: 1})
        for(i=0; person[i]; i++){
          await SCLtest.deleteMany({person_id: person[i].person_id})
        }
        await Class.deleteOne({class_id: req.body.class_id})
        await User.deleteMany({class_id: req.body.class_id})
        res.status(200).json({
            message: "success"
        })
    }
    catch(err){
        // console.log(err)
        res.status(400).json({
            message: err
        })
    }
}

//修改班级
exports.class_rename = async (req, res) => {
    var class_id = req.body.class_id ;
    var class_id_new = req.body.class_id_new ;
    var class_name_new = req.body.class_name_new ;
    try{
        var class_ = await Class.findOne({class_id : class_id_new})
        if(class_){
            res.status(402).json({
                message: "class number conflict"
            })
            return res.end() ;
        }
        if(class_name_new){
            await Class.updateOne({class_id: class_id}, {$set:{class_name :class_name_new}})
        }
        if(class_id_new){
            await Class.updateOne({class_id: class_id}, {$set: {class_id :class_id_new}})
        } 
        res.status(200).json({
            message: "success"
        })
    }
    catch(err){
        // console.log(err)
        res.status(400).json({
            message: err
        })
    }
}

//搜索班级
exports.class_search = async (req, res) => {
}
